package controller

import (
	"a-common/myerr"
	"a-payment/service"
	"log"
	"net/url"
	"sync"

	"github.com/gofiber/fiber/v2"
)

var (
	PayControllerTemp *PayController
	PayControllerOnce sync.Once
	PayService        = service.NewPayCallbackService()
)

type PayController struct{}

func NewPayController() *PayController {
	PayControllerOnce.Do(func() {
		PayControllerTemp = &PayController{}
	})
	return PayControllerTemp
}

// Callback 支付回调
func (m *PayController) Callback(c *fiber.Ctx) error {
	tag := c.Params("tag")
	if tag == "" {
		return myerr.ERR_SYS_ARGS
	}
	// 判断对应的回调处理
	if tag == "alipay" {
		params, err := url.ParseQuery(string(c.Body()))
		if err != nil {
			return err
		}
		err = PayService.AliCallback(params)
		if err != nil {
			return c.SendString("fail")
		}
		return c.SendString("success")
	} else if tag == "wepay" {
		params, err := url.ParseQuery(string(c.Body()))
		if err != nil {
			return err
		}
		err = PayService.WeCallback(params)
		if err != nil {
			return c.SendString("fail")
		}
		return c.SendString("success")
	} else if tag == "mpay" {
		log.Println("unknow")
	}
	return myerr.ERR_SYS_ARGS
}
